<template>
  <div>
    <BaseVxeGrid
      ref="vxeGridRef"
      :gridOptions="gridOptions"
      :columnStyles="columnStyles"
      :gridEvents="gridEvents"
      v-on="gridEvents"
      :loading="loading"
    >
      <template #repeatIndicator="{ row }">
        <div style="display: flex; align-items: center; justify-content: center; gap: 5px">
          <CusTag v-if="row.repeatIndicator == 0" type="success"> 短期 </CusTag>
          <CusTag v-else type="danger"> 长期 </CusTag>
        </div>
      </template>

      <template #action="{ row }">
        <button>clickMe_{{ row.special_msg }}</button>
      </template>
    </BaseVxeGrid>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import type { VxeGridListeners, VxeGridProps } from 'vxe-table'
import BaseVxeGrid from '../components/BaseVxeGrid.vue'
import type { IColumnStyles } from '@/components/BaseVxeType'
import type { ComponentExposed } from 'vue-component-type-helpers'
import CusTag from './components/cusTag.vue'

type RowVO = {
  orderKey: string
  titleMsg: string
  patientId: string
  mixOrderState: null
  mixTypeId: null
  mixMsg: null
  repeatIndicator: number
  mixCatalog: null
  route: string
  frequency: string
  orderStatus: number
  startDateTime: string
  stopDateTime: string
  speedDesc: string
  performSchedule: string
  mixUser: null
  mixTime: null
  processId: null
  processText: null
  processUser: null
  processTime: null
  orderPassTime: null
  orderPassUser: null
  refuseTime: null
  restoreTime: null
  restoreText: null
  orderNo: string
  enterDateTime: string
  createTime: string
}
// 列样式设置
const columnStyles: Array<IColumnStyles> = [
  {
    specifyField: 'drug_name',
    judgeField: 'drug_name',
    name: '抗生素',
    value: ['55555修改测试数据'],
    style: {
      backgroundColor: '#ff0000 ',
      color: 'white',
      fontStyle: 'italic',
      fontSize: '14px',
      fontWeight: 'bolder',
    },
  },
  {
    specifyField: 'drug_name',
    judgeField: 'drug_name',
    name: '人工贴签',
    value: ['■◎注射用硫酸长春新碱'],
    style: { backgroundColor: '#00ffff', color: '#ff0000', fontWeight: '900' },
  },
]

const vxeGridRef = ref<ComponentExposed<typeof BaseVxeGrid<RowVO>>>()

// https://vxetable.cn/#/component/grid/checkbox/range 滑动复选框多选
const gridOptions = ref<VxeGridProps<RowVO>>({
  // keyboardConfig: {
  // isEdit: true,
  // isArrow: true,
  // isEnter: true,
  // isTab: true,
  // isDel: true,
  // isBack: true,
  // isEsc: true,
  // editMethod({ $table, row, column }) {
  //   // https://vxetable.cn/#/component/grid/keyboard/editMethod 第二个 按键编辑表格
  //   // 清空值
  //   // if (column.field) {
  //   //   row[column.field] = ''
  //   // }
  //   // 激活编辑状态
  //   $table.setEditCell(row, column)
  // },
  // },
  // editConfig: {
  // trigger: 'dblclick',
  // mode: 'cell',
  // showStatus: true,
  // },
  virtualXConfig: {
    enabled: false,
  },
  virtualYConfig: {
    enabled: false,
  },
  spanMethod({ row, _rowIndex, column, visibleData }) {
    const $grid = vxeGridRef.value?.getVxeGridRef()
    if ($grid && $grid.isAggregateRecord(row)) {
      if (column.field === 'mixOrderState') {
        return { rowspan: 1, colspan: $grid.columns?.length ?? 0 }
      }
      return { rowspan: 0, colspan: 0 }
    }

    // 需要考虑到分组, 进行行合并, 如果上下行一致则进行合并
    const fields = ['mixOrderState', 'mixTypeId', 'mixMsg', 'repeatIndicator']
    if (!fields.includes(column.property)) {
      return { rowspan: 1, colspan: 1 }
    }

    const cellValue = (row as unknown as Record<string, unknown>)[column.property]
    const prevRow = visibleData[_rowIndex - 1]

    // 如果上一行存在且值相同（包括空值），则隐藏当前单元格
    if (prevRow && (prevRow as unknown as Record<string, unknown>)[column.property] === cellValue) {
      return { rowspan: 0, colspan: 0 }
    }

    // 计算向下合并的行数
    let countRowspan = 1
    let nextIndex = _rowIndex + 1

    while (
      nextIndex < visibleData.length &&
      (visibleData[nextIndex] as unknown as Record<string, unknown>)[column.property] === cellValue
    ) {
      countRowspan++
      nextIndex++
    }

    // 如果合并行数大于1，则返回合并结果
    if (countRowspan > 1) {
      return { rowspan: countRowspan, colspan: 1 }
    }

    return { rowspan: 1, colspan: 1 }
  },
  aggregateConfig: {
    groupFields: ['orderKey'],
    showTotal: true,
    contentMethod({ groupValue, children }) {
      return `${groupValue}-${children[0].titleMsg} 占满一行`
    },
  },
  columns: [
    // { minWidth: '100px', field: 'patientId', title: '患者ID' },
    { minWidth: '100px', field: 'mixOrderState', title: '审核状态', rowGroupNode: true },
    { minWidth: '100px', field: 'mixTypeId', title: '配伍关系I' },
    { minWidth: '100px', field: 'mixMsg', title: '审核说明' },
    {
      minWidth: '100px',
      field: 'repeatIndicator',
      title: '类型',
      slots: { default: 'repeatIndicator' },
    },
    { minWidth: '100px', field: 'mixCatalog', title: '分类' },
    { minWidth: '200px', field: 'orderText', title: '医嘱正文' },
    { minWidth: '100px', field: 'dosage', title: '剂量' },
    { minWidth: '100px', field: 'route', title: '途径' },
    { minWidth: '100px', field: 'frequency', title: '频次' },
    { minWidth: '100px', field: 'orderStatus', title: '医嘱状态' },
    { minWidth: '100px', field: 'startDateTime', title: '开始时间' },
    { minWidth: '100px', field: 'stopDateTime', title: '结束时间' },
    { minWidth: '100px', field: 'drugBillingAttr', title: '计价' },
    { minWidth: '100px', field: 'freqDetail', title: '说明' },
    { minWidth: '100px', field: 'speedDesc', title: '滴速' },
    { minWidth: '100px', field: 'performSchedule', title: '执行计划' },
    { minWidth: '100px', field: 'mixUser', title: '审查人' },
    { minWidth: '100px', field: 'mixTime', title: '审查时间' },
    { minWidth: '100px', field: 'processId', title: '点评分类' },
    { minWidth: '100px', field: 'processText', title: '点评意见' },
    { minWidth: '100px', field: 'processUser', title: '点评人' },
    { minWidth: '100px', field: 'ProcessTime', title: '点评时间' },
    { minWidth: '100px', field: 'orderPassTime', title: '放行时间' },
    { minWidth: '100px', field: 'orderPassUser', title: '放行人' },
    { minWidth: '100px', field: 'refuseTime', title: '拒发时间' },
    { minWidth: '100px', field: 'restoreTime', title: '恢复时间' },
    { minWidth: '100px', field: 'restoreText', title: '恢复说明' },
    { minWidth: '100px', field: 'orderNo', title: '组号' },
    { minWidth: '100px', field: 'enterDateTime', title: '录入时间' },
    { minWidth: '100px', field: 'CaeateTime', title: '同步时间' },
  ],
  data: [],
  menuConfig: {
    enabled: true,
    header: {},
    body: {},
    footer: {},
  },
})

import tData from './data/MergeCellsData.json'
import { ElTag } from 'element-plus'

// 扁平化数据, 将children数据与父级平级
const flatData: object[] = []
tData.forEach((item) => {
  const newItem = item
  newItem.hisOrderItemList.forEach((element) => {
    const newElement = { ...newItem, ...element }
    flatData.push(newElement)
  })
})
console.log('gridOptions.value.data', flatData)
gridOptions.value.data = flatData as unknown as RowVO[]

const loading = ref(false)

const gridEvents: VxeGridListeners<RowVO> = {
  // 禁止行编辑
  editDisabled({ row, column }) {
    console.log('禁止编辑', column.field, row)
  },
  // editActivated({ row }) {},
  sortChange({ sortList }) {
    console.info(sortList.map((item) => `${item.field},${item.order}`).join('; '))
  },
  menuClick({ menu, row, column }) {
    console.log('菜单点击', menu.code, row, column)
  },
}
</script>

<style scoped></style>
